package com.aplink.generic.util;

import java.util.Locale;

import android.content.Context;
import android.content.res.Configuration;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.aplink.generic.database.DatabaseHelper;
import com.aplink.generic.dictionary.GenericDictionary;
import com.aplink.generic.sharepreference.GenericSharePreference;
import com.aplink.sg.R;

public class Language {
	public static final String COLUMN_LANGUAGE_NAME = "LanguageID";
	public static final String DEFAULT_LANGUAGE = "English";
	public static final String DEFAULT_LANGUAGE_CODE = "en_SG";
	private static Language sIntance = null;
	public static final String TABLE_LANGUAGE = "Language";
	public static final String TABLE_TRANSLATION = "Translation";

	public static Language getInstance() {
		synchronized (Language.class) {
			if (sIntance == null) {
				sIntance = new Language();
			}
			return sIntance;
		}
	}

	private GenericDictionary<String, GenericDictionary<String, String>> mDictionary;

	private Language() {
		initDictionary();
	}

	public String get(CharSequence charSequence) {
		return get(charSequence.toString());
	}

	public String get(String text) {
		String targetLanguage = GenericSharePreference.getInstance()
				.getCurrentLanguage();
		if (TextUtils.isEmpty(targetLanguage)
				|| targetLanguage.equalsIgnoreCase(Language.DEFAULT_LANGUAGE)) {
			return text;
		}
		String key = text.trim().toLowerCase(Locale.getDefault())
				.replaceAll(":", "");
		if (mDictionary.containsKey(key)
				&& mDictionary.get(key).containsKey(targetLanguage)) {
			return mDictionary.get(key).get(targetLanguage);
		}
		return text;
	}

	public void initDictionary() {
		mDictionary = DatabaseHelper.getInstance().getTranslationDictionary();
	}

	public void setText(View view, String text) {
		if (view instanceof TextView) {
			if (view.getTag(R.id.TEXT_ENGLISH) == null) {
				view.setTag(R.id.TEXT_ENGLISH, text);
			}
			((TextView) view).setText(get((CharSequence) view
					.getTag(R.id.TEXT_ENGLISH)));
		}
	}

	public void updateConfiguration(Context context) {
		Locale locale = new Locale(GenericSharePreference.getInstance()
				.getLanguageCode());
		Locale.setDefault(locale);
		Configuration config = new Configuration();
		config.locale = locale;
		context.getResources().updateConfiguration(config,
				context.getResources().getDisplayMetrics());
	}
}
